import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { LocalStorageVar } from '@/utils/localStorage'
import { AppStaticData } from '@/initialization/InitAppStaticData'

const localStorageId = 'UserInfo'
export const useUserInfoStore = defineStore('UserInfo', () => {
  const username = ref('')
  const hasLogin = computed(() => !!username.value)
  const usernameLocal = new LocalStorageVar(username.value, `${localStorageId}:username`)

  function initUser() {
    usernameLocal.init()
    username.value = usernameLocal.data
  }

  function login(un: string) {
    username.value = un
    usernameLocal.set(un)
    AppStaticData.username = un
  }
  function logout() {
    username.value = ''
    usernameLocal.clear()
    AppStaticData.username = ''
  }

  return { initUser, username, hasLogin, login, logout }
})
